<template>
  <div>
    <el-row>
      <el-col :span="18">
        <el-form :model="searchForm" label-width="60px" :inline="true">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getTableData">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-button type="danger" style="float: right; margin-left: 20px" @click="handlerDel()"
          >删除</el-button
        >
        <el-button type="primary" style="float: right" @click="handleAdd()">新增</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :empty-text="'暂无数据'"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          @change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const searchForm = reactive({
  username: ''
})
const tableData = ref([])
const multipleSelection = ref([])
const pageNum = ref(1)
const pageSize = ref(8)
const total = ref(0)

onMounted(async () => {
  getTableData()
})

const getTableData = async () => {
  let whereStr = ''
  if (searchForm.username) {
    whereStr = `where username like '%${searchForm.username}%'`
  }

  let totalRes = await window.db.select(`select count(1) total from user ${whereStr}`)
  total.value = totalRes[0].total

  const offset = (pageNum.value - 1) * pageSize.value
  const limit = pageSize.value
  let res = await window.db.select(`select * from user ${whereStr} LIMIT ${offset}, ${limit}`)
  tableData.value = res
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleCurrentChange = (currentPage: number, size: number) => {
  pageNum.value = currentPage
  pageSize.value = size
  getTableData()
}

const handleAdd = async () => {
  router.push({ path: '/user/edit', query: { showBack: true, from: '/user' } })
}

const handleEdit = async (index, row) => {
  router.push({ path: '/user/edit', query: { showBack: true, data: JSON.stringify(row) } })
}

const handlerDel = async () => {
  let ids = multipleSelection.value.map((user) => user.id)
  if (ids.length <= 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('是否确定删除?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await window.db.update(
      `delete from user where id in (${Array.from({ length: ids.length }, () => '?').join(',')})`,
      ...ids
    )
    getTableData()
  })
}
const reset = () => {
  searchForm.username = ''
  pageNum.value = 1
  getTableData()
}
</script>

<style lang="scss" scoped></style>
